package com.star.common.oss.service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 抽象oss处理层
 *
 * @author zhouhengzhe #公众号：小白的Java进阶之路
 * @version 1.0
 * @date 2023/6/27 14:06
 */
public abstract class AbstractOssClient implements OssClient {

    /**
     * 检查对象的所有属性不为空
     *
     * @param obj 对象
     */
    public void checkAllPropertiesNotNull(Object obj) {
        try {

            Class<?> objClass = obj.getClass();
            Field[] fields = objClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value == null) {
                    throw new IllegalAccessException(String.format("Field '%s.%s' is null", objClass.getSimpleName(), field.getName()));
                } else if (value instanceof String && ((String) value).isEmpty()) {
                    throw new IllegalAccessException(String.format("Field '%s.%s' is empty", objClass.getSimpleName(), field.getName()));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 检查多个属性不为空
     *
     * @param props 属性
     */
    public void checkProperties(String... props) {
        List<String> emptyProps = new ArrayList<>();
        for (String prop : props) {
            if (prop == null || prop.trim().isEmpty()) {
                emptyProps.add(prop);
            }
        }

        if (!emptyProps.isEmpty()) {
            String errorMsg = "Following properties are empty: " + String.join(", ", emptyProps) + ".";
            throw new IllegalArgumentException(errorMsg);
        }
    }
}
